//-------------------------------------------------------------------
//	Copyright (c) 2012-2014 Zhirnov Andrey
//	This file is part of the "UXGEN-ES" project.
//	See copyright notice in "Engine.h".
//-------------------------------------------------------------------

#include "Graphics/Loaders/SpriteLoader.h"
#include "Graphics/MetaData/Meta.Sprite.h"

namespace Engine
{
namespace Graphics
{
	
/*
=================================================
	constructor
=================================================
*/
	SpriteLoader::SpriteLoader ()
	{
	}
		
/*
=================================================
	Register
=================================================
*/
	void SpriteLoader::Register (ResourceManager *rm)
	{
		rm->RegisterLoader( EResource::SPRITE_2D, &Load, null, this );
	}

/*
=================================================
	Unregister
=================================================
*/
	void SpriteLoader::Unregister (ResourceManager *rm)
	{
		rm->UnregisterLoader( EResource::SPRITE_2D, &Load, null, this );
	}
	
/*
=================================================
	Load
=================================================
*/
	bool SpriteLoader::Load (ResourcePtr &resource, const RFilePtr &file, void *parameter,
							 const Resource::ResLoadParams &loadParams, const EngineSubSystemsRef ess)
	{
		CHECK_ERR( loadParams.Is< Sprite2D::SpriteLoadParams >() );

		return _LoadSprite( resource, file, parameter, loadParams.To< Sprite2D::SpriteLoadParams >(), ess );
	}
	
/*
=================================================
	_LoadSprite
=================================================
*/
	bool SpriteLoader::_LoadSprite (ResourcePtr &resource, const RFilePtr &file, void *parameter,
									const Sprite2D::SpriteLoadParams &loadParams, const EngineSubSystemsRef ess)
	{
		RESFILE_CHECK_HEADER( file, SpriteFileInfo );

		MetaData::Sprite2dCfg		cfg;
		CHECK_ERR( cfg.Deserialize( file ) );

		Sprite2DPtr	sprite = Sprite2D::New( ess );

		cfg.Init( sprite.ptr(), ess );

		CHECK_ERR( TextureLoader::_LoadTex( &sprite->_texture, file, null, Texture::GetDefaultLoadParams(), ess ) );

		sprite->_material.ResetTextures();
		sprite->_material.SetTexture( 0, &sprite->_texture );

		resource = sprite;
		return true;
	}


}	// Graphics
}	// Engine